package cn.xing.managementSystem.service;

import cn.xing.managementSystem.bean.pageable.PageableConverter;
import cn.xing.managementSystem.bean.pageable.PageableRequest;
import cn.xing.managementSystem.bean.pageable.PageableResponse;
import cn.xing.managementSystem.domain.ImageStore;
import cn.xing.managementSystem.domain.Student;
import cn.xing.managementSystem.repository.StudentRepository;
import cn.xing.managementSystem.utils.Preconditions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * @author cuixing
 * @package cn.xing.managementSystem.service
 * @class StudentService
 * @email xing.cui@magicwindow.cn
 * @date 2018/4/25 下午1:34
 * @description
 */

@Service
public class StudentService {

    @Autowired
    private StudentRepository studentRepository;

    @Autowired
    private ImageStoreService imageStoreService;

    public PageableResponse<Student> listPageable(PageableRequest pageableRequest){
        PageableResponse<Student> response = new PageableResponse<>();
        Page<Student> page = studentRepository.findByDeletedIsFalse(PageableConverter.toPageRequest(pageableRequest));
        response.setList(page.getContent());
        response.setTotalCount(page.getTotalElements());
        response.setTotalPages(page.getTotalPages());
        response.setCurPage(pageableRequest.getPageNumber() + 1);
        return response;
    }

    public Student saveStudent(Student student) {
        return studentRepository.saveAndFlush(student);
    }

    public boolean saveStudentAndImageStore(Student student, Long studentImageId, MultipartFile studentImageFile) throws IOException {
        if(Preconditions.isBlank(studentImageId) && Preconditions.isNotBlank(studentImageFile)){
            ImageStore imageStore = imageStoreService.saveImageStore(studentImageFile);
            student.setImageStore(imageStore);
        }
        student = studentRepository.saveAndFlush(student);
        return Preconditions.isNotBlank(student);
    }

    public Student findById(Long id){
        return studentRepository.findByIdAndAndDeletedIsFalse(id);

    }


    public List<Student> findAllStudent(){
        return studentRepository.findByDeletedIsFalse();

    }
}